<?php

namespace App\Http\Controllers\Freelancer;

use App\Http\Controllers\Controller;
use App\Models\Task;
use App\Models\ContractSignHistory;
use App\Services\ContractSign\ContractSigner;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Validator;

class ContractSignController extends Controller
{
    protected ContractSigner $contractSigner;

    public function __construct(ContractSigner $contractSigner)
    {
        $this->contractSigner = $contractSigner;
    }

    public function sign(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'taskId' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 1,
                'message' => '参数验证失败',
                'data' => $validator->errors(),
            ]);
        }

        $freelancer = $request->user();

        if ($freelancer->verification_status != 'approved') {
            return response()->json([
                'code' => 1,
                'message' => '请先完成实名认证后再进行签署',
                'data' => null,
            ]);
        }

        $task = Task::find($request->input('taskId'));
        if (! $task) {
            return response()->json([
                'code' => 1,
                'message' => '任务不存在',
                'data' => null,
            ]);
        }

        $task->loadMissing('tenant');
        if (empty($task->tenant->name)) {
            return response()->json([
                'code' => 1,
                'message' => '任务方设定有误',
                'data' => null,
            ]);
        }
        $now = Carbon::now();

        $params = [
            'contractName' => $task->name,
            //公司侧参数
            'fullNameLyp'     => config('contract-sign.drivers.junziqian.full_name_lyp'),
            'identityCardLyp' => config('contract-sign.drivers.junziqian.identity_card_lyp'),
            'emailLyp'        => config('contract-sign.drivers.junziqian.email_lyp'),
            'chapteNameLyp'   => config('contract-sign.drivers.junziqian.chapte_name_lyp'),
            'signIdLyp'       => config('contract-sign.drivers.junziqian.default_sign_id'),
            //C端用户参数
            'fullName' => $freelancer->real_name ?? $freelancer->name,
            'identityCard' => $freelancer->id_card,
            'identityType' => 1,
            'mobile' => $freelancer->phone,
            'tenantName' => $task->tenant->name,
            'taskName' => $task->name,
            'templateNo' => config('contract-sign.drivers.junziqian.default_template_no'),
            'chapteName' => 'ebq',
            'serverCa' => 1,
            'dealType' => 5,
            'authLevel' => '[11]',
            'year' => $now->year,
            'month' => $now->month,
            'day' => $now->day,
            'backUrl' => $request->input('returnUrl'),
            'notifyUrl' => route('contract-sign.notify', [], true),
        ];

        $result = $this->contractSigner->applySign($params);

        if ($result->success) {
            $applyNo = $result->data['applyNo'] ?? null;

            if ($applyNo) {
                ContractSignHistory::create([
                    'task_id' => $task->id,
                    'freelancer_id' => $freelancer->id,
                    'apply_no' => $applyNo,
                    'status' => 'pending',
                ]);
            }

            return response()->json([
                'code' => 0,
                'message' => $result->message,
                'data' => [
                    'shortUrl' => $result->data['signUrl'] ?? '',
                    'applyNo' => $applyNo ?? '',
                ],
            ]);
        }

        return response()->json([
            'code' => 1,
            'message' => $result->message,
            'data' => [
                'code' => $result->code,
                'context' => $result->context,
            ],
        ]);
    }
}
